/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <sys/types.h>
#include <thread>
#include <fcntl.h>
#include <unistd.h>

#include "sle_host_event_handler.h"
#include "sle_host_server.h"
#include "sle_host_service.h"
#include "sle_seek_server.h"
#include "sle_announce_server.h"
#include "sle_connect_server.h"
#include "sle_ssap_client_server.h"
#include "sle_ssap_server_server.h"
#include "sle_adapter_manager.h"
#include "sle_flow_monitor_manager.h"
#include "sle_utils_remote_observer_list.h"
#include "sle_common_config.h"
#include "sle_hilog.h"
#include "sle_host_config_manager.h"
#include "sle_connect_config_manager.h"
#include "sle_advanced_setting_manager.h"

#ifndef SLE_LOG_FILE_PATH
#define SLE_LOG_FILE_PATH "data/nearlink_sle/device_log/"
#define SLE_SDK_LOG SLE_LOG_FILE_PATH"sle_sdk.log"
#define SLE_SDK_BAK_LOG SLE_LOG_FILE_PATH"sle_sdk.log.bak"
#endif

namespace OHOS {
namespace NearLink {
namespace SleStandard {
namespace {
constexpr const char *SLE_HOST_RUNNER_WORK_THREAD = "SLE_HOST_RUNNER_WORK_THREAD";
constexpr uint16_t CHECK_SLE_DRIVER_RETRY_TIMES = 10;
constexpr uint32_t CHECK_SLE_DRIVER_FAIL_SLEEP = 2;
}

class SleHostServer::SleHostServerImpl {
public:
    SleHostServerImpl();
    ~SleHostServerImpl();

    SleErrorCode CheckOperation();
    SleErrorCode RegisterHostCallback(const sptr<ISleHostCallback> &callback);
    SleErrorCode UnregisterHostCallback(const sptr<ISleHostCallback> &callback);
    SleErrorCode EnableSle();
    SleErrorCode DisableSle();
    SleErrorCode GetSleState(int32_t &state);
    SleErrorCode GetHostAddress(SleAddress &address);
    SleErrorCode SetHostName(const std::string name);
    SleErrorCode GetHostName(std::string &name);
    SleErrorCode StartFlowMonitor();
    SleErrorCode StopFlowMonitor();
    SleErrorCode GetHostDefaultConnectConfig(SleConnectConfig &hostConnParam);
    sptr<IRemoteObject> GetSleServerRemote(const std::string &name);
    SleErrorCode CreateSleServers();
    void InitSleHostConfig();

    class SleAdapterManagerCallback;
    std::unique_ptr<SleAdapterManagerCallback> adapterCbImpl_ = nullptr;
    class SleFlowMonitorManagerCallback;
    std::unique_ptr<SleFlowMonitorManagerCallback> monitorCkImpl_ = nullptr;

    SleHostService *hostService_ = nullptr;
    SleAdapterManager *adapterManager_ = nullptr;
    SleFlowMonitorManager *monitorManager_ = nullptr;
    std::unique_ptr<SleHostConfigManager> hostConfigManager_ = nullptr;
    std::shared_ptr<AppExecFwk::EventRunner> hostEventRunner_ = nullptr;
    std::shared_ptr<SleHostEventHandler> hostEventHandler_  = nullptr;

    std::map<std::string, sptr<IRemoteObject>> servers_;
    SleRemoteObserverList<ISleHostCallback> callbacks_;
};

class SleHostServer::SleHostServerImpl::SleAdapterManagerCallback : public ISleAdapterManagerCallback {
public:
    SleAdapterManagerCallback(SleHostServer::SleHostServerImpl &impl) : impl_(impl){};
    ~SleAdapterManagerCallback() = default;

    void OnSleStateChange(const SleDeviceState state) override;

private:
    SleHostServer::SleHostServerImpl &impl_;
};

class SleHostServer::SleHostServerImpl::SleFlowMonitorManagerCallback : public ISleFlowMonitorManagerCallback {
public :
    SleFlowMonitorManagerCallback(SleHostServer::SleHostServerImpl &impl) : impl_(impl){};
    ~SleFlowMonitorManagerCallback() = default;

    void OnFlowMonitorEvent(float flow) override
    {
        SLE_LOGD("OnFlowMonitorEvent In");
        impl_.callbacks_.ForEach([flow](sptr<ISleHostCallback> callback) {
            callback->OnFlowMonitorEvent(flow);
        });
    }

private:
    SleHostServer::SleHostServerImpl &impl_;
};

// TODO start 后续在hdi实现，提供hdi接口
typedef enum {
    KHP_SLE_CHAN_NETLINK_HCI = 23,
    KHP_SLE_CHAN_NETLINK_TM,
} sle_chan_netlink_protocol_tt;

typedef enum {
    KHP_SLE_CHAN_USER_PORT_HCI = 100,
    KHP_SLE_CHAN_USER_PORT_TM,
} sle_chan_user_port_tt;

static SleErrorCode CheckSleDriver(void)
{
    uint16_t retry = 0;
    while (retry < CHECK_SLE_DRIVER_RETRY_TIMES)
    {
        int fd = open("/dev/hwsle", O_RDWR);
        if (fd == -1) {
            // 打开设备失败
            ++retry;
            SLE_LOGE("open /dev/hwsle fail, err[%{public}d, (%{public}s)], retry[%{public}d]", errno, strerror(errno), retry);
            sleep(CHECK_SLE_DRIVER_FAIL_SLEEP);//sleep 2 seconds
            continue;
        }
        SLE_LOGI("open /dev/hwsle success");
        close(fd);
        return SLE_NO_ERROR;
    }
    return SLE_ERR_NOT_READY;
}

void SleHostServer::SleHostServerImpl::SleAdapterManagerCallback::OnSleStateChange(const SleDeviceState state)
{
    SLE_LOGD("OnSleStateChange In");
    impl_.callbacks_.ForEach([state](sptr<ISleHostCallback> callback) {
        callback->OnSleStateChange(state);
    });
    impl_.hostEventHandler_->SendEvent(static_cast<uint32_t>(SleHostEvent::MSG_STATE_CHANGE), state, 0);
    if(state != SLE_HOST_STATE_ENABLED && state !=  SLE_HOST_STATE_DISABLED) return;
    SLE_ASSERT_AND_RETURN(impl_.hostConfigManager_ != NULL);
    SleErrorCode ret = impl_.hostConfigManager_->SetLastHostState(state);
    SLE_ASSERT_AND_RETURN(ret == SLE_NO_ERROR);

    std::string hostName;
    ret = impl_.hostConfigManager_->GetHostName(hostName);
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "GetHostName failed(%{public}d)", ret);
    if(hostName == SLE_HOST_NAME_PRE_FIX || hostName.empty()) {
        SleDeviceAddress hostAddrStruct = {
            .addrType = SLE_PUBLIC_ADDRESS_TYPE,
        };
        //向底层获取mac地址，存入config文件
        SleAddress sleHostAddr(hostAddrStruct);
        SleErrorCode ret = impl_.hostService_->GetHostAddress(sleHostAddr);
        SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "get local address failed(%{public}d)!", ret);
        hostAddrStruct = sleHostAddr.ConvertToSleDeviceAddress();
        ret = impl_.hostConfigManager_->SetHostAddr(hostAddrStruct.addr);
        SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "GetHostAddr failed(%{public}d)", ret);
        //取mac地址后两位设置为host name
        char hostNameChar[SLE_DEVICE_NAME_LEN] = SLE_HOST_NAME_PRE_FIX;
        sprintf(hostNameChar + SLE_HOST_NAME_PRE_FIX_LEN, "%02X%02X", hostAddrStruct.addr[4], hostAddrStruct.addr[5]);
        hostName = hostNameChar;
        ret = impl_.hostService_->SetHostName(hostName);
        SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "get local address failed(%{public}d)!", ret);
        ret = impl_.hostConfigManager_->SetHostName(hostName);
        SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "SetHostName failed(%{public}d)!", ret);
    }
}

void SleHostServer::SleHostServerImpl::InitSleHostConfig()
{
    SLE_LOGD("enter");
    SleErrorCode ret = SLE_ERR_UNKNOWN;
    //防止驱动未初始化
    ret = CheckSleDriver();
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "sle driver not init");
    AdvancedSettingManager::GetInstance()->InitAdvancedSettingManager();
    hostConfigManager_ = std::make_unique<SleHostConfigManager>("sle_host_config.cfg");
    SLE_ASSERT_AND_RETURN_LOG(hostConfigManager_ != NULL, "hostConfigManager_ null fail");
    std::string hostName;
    // 开机自动EnableSle
    bool isAutoEnableSle;
    SleDeviceState hostState;
    ret = hostConfigManager_->GetIsAutoEnableSle(isAutoEnableSle);
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "GetIsAutoEnableSle failed(%{public}d)", ret);
    ret = hostConfigManager_->GetLastHostState(hostState);
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "GetLastHostState failed(%{public}d)", ret);
    //TODO: bug:当前重启后hostState读出为0（disable）
    // if(isAutoEnableSle == true && hostState == 1) {
    if(isAutoEnableSle) {
        // ret = adapterManager_->Disable();
        // SLE_ASSERT_AND_PRINT_LOG(ret == SLE_NO_ERROR, "disenable sle failed(%{public}d)!", ret);
        ret = adapterManager_->Enable();
        SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "enable sle failed(%{public}d)!", ret);
    } else {
        SLE_LOGI("isAutoEnableSle == %{public}d, LastHostState= %{public}d", isAutoEnableSle, hostState);
    }
}
// TODO end

SleHostServer::SleHostServerImpl::SleHostServerImpl()
{
    SLE_LOGD("SleHostServerImpl In");
    hostService_ = SleHostService::GetInstance();
    SLE_ASSERT_AND_RETURN_LOG(hostService_, "host service instance null error!");

    adapterManager_ = SleAdapterManager::GetInstance();
    SLE_ASSERT_AND_RETURN_LOG(adapterManager_, "adapter manager instance null error!");
    monitorManager_ = SleFlowMonitorManager::GetInstance();
    SLE_ASSERT_AND_RETURN_LOG(monitorManager_, "monitor manager instance null error!");

    adapterCbImpl_ = std::make_unique<SleAdapterManagerCallback>(*this);
    SLE_ASSERT_AND_RETURN_LOG(adapterCbImpl_, "adapter manager callback error!");
    SleErrorCode ret = adapterManager_->RegisterAdapterCallback(*adapterCbImpl_.get());
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "register adapter manager callback failed(%{public}d)!", ret);

    monitorCkImpl_ = std::make_unique<SleFlowMonitorManagerCallback>(*this);
    SLE_ASSERT_AND_RETURN_LOG(monitorCkImpl_, "monitor manager callback error!");
    ret = monitorManager_->RegisterMonitorCallback(*monitorCkImpl_.get());
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "register monitor manager callback failed(%{public}d)!", ret);

    hostConfigManager_ = std::make_unique<SleHostConfigManager>();
    SLE_ASSERT_AND_RETURN_LOG(hostConfigManager_ != NULL, "create hostConfigManager_ fail");

    hostEventRunner_ = AppExecFwk::EventRunner::Create(SLE_HOST_RUNNER_WORK_THREAD);
    SLE_ASSERT_AND_RETURN_LOG(hostEventRunner_ != nullptr, "create hostEventRunner_ fail");
    hostEventHandler_ = std::make_shared<SleHostEventHandler>(hostEventRunner_);
    SLE_ASSERT_AND_RETURN_LOG(hostEventHandler_ != nullptr, "create hostEventHandler_ fail");
}

SleHostServer::SleHostServerImpl::~SleHostServerImpl()
{
    SLE_LOGD("~SleHostServerImpl In");
    SLE_ASSERT_AND_RETURN_LOG(adapterManager_, "adapter manager instance null error!");
    SLE_ASSERT_AND_RETURN_LOG(adapterCbImpl_, "adapter manager callback error!");

    SleErrorCode ret = adapterManager_->UnregisterAdapterCallback(*adapterCbImpl_.get());
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "unregister adapter manager callback failed(%{public}d)!", ret);

    SLE_ASSERT_AND_RETURN_LOG(monitorManager_, "monitor manager instance null error!");
    SLE_ASSERT_AND_RETURN_LOG(monitorCkImpl_, "monitor manager callback error!");
    ret = monitorManager_->UnregisterMonitorCallback(*monitorCkImpl_.get());
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "unregister monitor manager callback failed(%{public}d)!", ret);
}

SleErrorCode SleHostServer::SleHostServerImpl::CheckOperation()
{
    SLE_ASSERT_AND_RETURN_RET_LOG(hostService_, SLE_ERR_NOT_READY, "host service instance null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(adapterManager_, SLE_ERR_NOT_READY, "adapter manager instance null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(monitorManager_, SLE_ERR_NOT_READY, "monitor manager instance null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(hostConfigManager_, SLE_ERR_NOT_READY, "connect config manager instance null error!");
    int32_t state;
    SleErrorCode ret = adapterManager_->GetState(state);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "get sle state failed(%{public}d)!", ret);
    SLE_ASSERT_AND_RETURN_RET_LOG(state == SLE_HOST_STATE_ENABLED, SLE_ERR_STATUS_WRONG,
        "host state(%{public}s) error!", SleDeviceStateStr(state));
    return SLE_NO_ERROR;
}


SleErrorCode SleHostServer::SleHostServerImpl::RegisterHostCallback(const sptr<ISleHostCallback> &callback)
{
    SLE_LOGD("RegisterHostCallback In");
    auto func = std::bind(&SleHostServer::SleHostServerImpl::UnregisterHostCallback, this, std::placeholders::_1);
    SLE_ASSERT_AND_RETURN_RET_LOG(callbacks_.Register(callback, func), SLE_ERR_FAILED, "register host callback failed!");
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::SleHostServerImpl::UnregisterHostCallback(const sptr<ISleHostCallback> &callback)
{
    SLE_LOGD("UnregisterHostCallback In");
    SLE_ASSERT_AND_RETURN_RET_LOG(callbacks_.Unregister(callback), SLE_ERR_FAILED, "unregister host callback failed!");
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::SleHostServerImpl::EnableSle()
{
    SLE_LOGD("EnableSle In");
    SleErrorCode ret = adapterManager_->Enable();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "enable sle failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::SleHostServerImpl::DisableSle()
{
    SLE_LOGD("DisableSle In");
    SleErrorCode ret = adapterManager_->Disable();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "disable sle failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::SleHostServerImpl::GetSleState(int32_t &state)
{
    SLE_LOGD("GetState In");
    SleErrorCode ret = adapterManager_->GetState(state);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "get sle state failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::SleHostServerImpl::GetHostAddress(SleAddress &address)
{
    SLE_LOGD("GetHostAddress In");
    SleErrorCode ret = hostService_->GetHostAddress(address);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "get local address failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::SleHostServerImpl::SetHostName(const std::string name)
{
    SLE_LOGD("SetHostName In");
    SleErrorCode ret = hostService_->SetHostName(name);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "set local name failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::SleHostServerImpl::GetHostName(std::string &name)
{
    SLE_LOGD("GetHostName In");
    SleErrorCode ret = hostService_->GetHostName(name);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "get local name failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::SleHostServerImpl::StartFlowMonitor()
{
    SLE_LOGD("StartFlowMonitor In");
    SleErrorCode ret = monitorManager_->StartFlowMonitor();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "start floaw monitor failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::SleHostServerImpl::StopFlowMonitor()
{
    SLE_LOGD("StartFlowMonitor In");
    SleErrorCode ret = monitorManager_->StopFlowMonitor();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "stop floaw monitor failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::SleHostServerImpl::GetHostDefaultConnectConfig(SleConnectConfig &hostConnParam)
{
    SLE_LOGD("GetHostDefaultConnectConfig In");
    SleErrorCode ret = AdvancedSettingManager::GetInstance()->GetHostDefaultConnectConfig(hostConnParam);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "get host connect config failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

sptr<IRemoteObject> SleHostServer::SleHostServerImpl::GetSleServerRemote(const std::string &name)
{
    SLE_LOGD("GetSleServerRemote %{public}s ", name.c_str());
    auto iter = servers_.find(name);
    if (iter != servers_.end()) {
        return servers_[name];
    }
    return nullptr;
}

SleErrorCode SleHostServer::SleHostServerImpl::CreateSleServers()
{
    sptr<SleAnnounceServer> announceServer = new SleAnnounceServer();
    SLE_ASSERT_AND_RETURN_RET_LOG(announceServer, SLE_ERR_NOT_READY, "create announce server failed!");
    servers_[SLE_ANNOUNCE_SERVER] = announceServer->AsObject();

    sptr<SleSeekServer> seekServer = new SleSeekServer();
    SLE_ASSERT_AND_RETURN_RET_LOG(seekServer, SLE_ERR_NOT_READY, "create seek server failed!");
    servers_[SLE_SEEK_SERVER] = seekServer->AsObject();

    sptr<SleConnectServer> connectServer = new SleConnectServer();
    SLE_ASSERT_AND_RETURN_RET_LOG(connectServer, SLE_ERR_NOT_READY, "create connect server failed!");
    servers_[SLE_CONNECT_SERVER] = connectServer->AsObject();

    sptr<SleSsapClientServer> clientServer = new SleSsapClientServer();
    SLE_ASSERT_AND_RETURN_RET_LOG(clientServer, SLE_ERR_NOT_READY, "create ssap client server failed!");
    servers_[SLE_SSAP_CLIENT_SERVER] = clientServer->AsObject();

    sptr<SleSsapServerServer> serverServer = new SleSsapServerServer();
    SLE_ASSERT_AND_RETURN_RET_LOG(serverServer, SLE_ERR_NOT_READY, "create ssap server server failed!");
    servers_[SLE_SSAP_SERVER_SERVER] = serverServer->AsObject();
    return SLE_NO_ERROR;
}

SleHostServer::SleHostServer()
    : SystemAbility(KH_SLE_SERVICE_SYS_ABILITY_ID_, true), registeredToService_(false), state_(ServiceRunningState::STATE_IDLE)
{
    SLE_LOGD("SleHostServer In");
    pimpl_ = std::make_unique<SleHostServerImpl>();
    SLE_ASSERT_AND_RETURN_LOG(pimpl_, "pimpl null error!");
}

SleHostServer::~SleHostServer()
{
    SLE_LOGD("~SleHostServer In");
}

std::mutex SleHostServer::instanceLock_;
sptr<SleHostServer> SleHostServer::instance_;

const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(SleHostServer::GetInstance().GetRefPtr());

sptr<SleHostServer> SleHostServer::GetInstance()
{
    std::lock_guard<std::mutex> autoLock(instanceLock_);
    if (instance_ == nullptr) {
        sptr<SleHostServer> temp = new SleHostServer();
        instance_ = temp;
    }
    return instance_;
}

void SleHostServer::OnStart()
{
    SLE_LOGI("OnStart In");
    SLE_ASSERT_AND_RETURN_LOG(state_ != ServiceRunningState::STATE_RUNNING, "service is already started error!");
    if (Init() != SLE_NO_ERROR) {
        SLE_LOGE("initiation failed!");
        OnStop();
        return;
    }
    //TODO:考虑sdk日志过大时的情况
    int ret = rename(SLE_SDK_LOG, SLE_SDK_BAK_LOG);
    SLE_ASSERT_AND_PRINT_LOG(
        ret == 0, "rename fail(%{public}d)  errno=%{public}d, (%{public}s)\n", ret, errno, strerror(errno));
    auto fp = freopen(SLE_SDK_LOG, "w", stdout);
    SLE_ASSERT_AND_PRINT_LOG(fp, "freopen stdout errno=%{public}d, (%{public}s)\n", errno, strerror(errno));
    fp = freopen(SLE_SDK_LOG, "w", stderr);
    SLE_ASSERT_AND_PRINT_LOG(fp, "freopen stderr errno=%{public}d, (%{public}s)\n", errno, strerror(errno));

    state_ = ServiceRunningState::STATE_RUNNING;
    std::thread tInitSleConfig([this]() { pimpl_->InitSleHostConfig(); });
    tInitSleConfig.detach();
    SLE_LOGI("service has been started successfully");
}

void SleHostServer::OnStop()
{
    SLE_LOGI("OnStop In");
    state_ = ServiceRunningState::STATE_IDLE;
    registeredToService_ = false;
}

SleErrorCode SleHostServer::Init()
{
    SLE_LOGI("Init In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->hostService_, SLE_ERR_NOT_READY, "host service instance null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->adapterManager_, SLE_ERR_NOT_READY, "adapter manager instance null error!");
    SleErrorCode ret = pimpl_->adapterManager_->Start();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "adapter manager start failed(%{public}d)!", ret);
    ret = pimpl_->CreateSleServers();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "create servers failed(%{public}d)!", ret);
    SLE_ASSERT_AND_RETURN_RET_LOG(!registeredToService_, SLE_NO_ERROR, "already inited!");
    bool result = Publish(SleHostServer::GetInstance());
    SLE_ASSERT_AND_RETURN_RET_LOG(result, SLE_ERR_FAILED, "init publish failed!");
    registeredToService_ = true;
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::RegisterHostCallback(const sptr<ISleHostCallback> &callback)
{
    SLE_LOGD("RegisterHostCallback In");
    SLE_ASSERT_AND_RETURN_RET_LOG(callback, SLE_ERR_INVALID_PARAM, "callback null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_NOT_READY, "pimpl null error!");
    SleErrorCode ret = pimpl_->RegisterHostCallback(callback);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "register sle callback failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::UnregisterHostCallback(const sptr<ISleHostCallback> &callback)
{
    SLE_LOGD("UnregisterHostCallback In");
    SLE_ASSERT_AND_RETURN_RET_LOG(callback, SLE_ERR_INVALID_PARAM, "callback null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_NOT_READY, "pimpl null error!");
    SleErrorCode ret = pimpl_->UnregisterHostCallback(callback);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "unregister sle callback failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::EnableSle()
{
    SLE_LOGD("EnableSle In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_NOT_READY, "pimpl null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->adapterManager_, SLE_ERR_NOT_READY, "adapter manager instance null error!");
    SleErrorCode ret = pimpl_->EnableSle();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "enable sle failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::DisableSle()
{
    SLE_LOGD("DisableSle In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_NOT_READY, "pimpl null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->adapterManager_, SLE_ERR_NOT_READY, "adapter manager instance null error!");
    SleErrorCode ret = pimpl_->DisableSle();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "disable sle failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::GetSleState(int32_t &state)
{
    SLE_LOGD("GetState In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_NOT_READY, "pimpl null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->adapterManager_, SLE_ERR_NOT_READY, "adapter manager instance null error!");
    SleErrorCode ret = pimpl_->GetSleState(state);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "get sle state failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::GetHostAddress(SleAddress &address)
{
    SLE_LOGD("GetHostAddress In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_NOT_READY, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed(%{public}d)!", ret);
    ret = pimpl_->GetHostAddress(address);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "get local address failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::SetHostName(const std::string name)
{
    SLE_LOGD("SetHostName In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_NOT_READY, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed(%{public}d)!", ret);
    ret = pimpl_->SetHostName(name);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "set local name failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::GetHostName(std::string &name)
{
    SLE_LOGD("GetHostName In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_NOT_READY, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed(%{public}d)!", ret);
    ret = pimpl_->GetHostName(name);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "get local name failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::StartFlowMonitor()
{
    SLE_LOGD("StartFlowMonitor In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_NOT_READY, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed(%{public}d)!", ret);
    ret = pimpl_->StartFlowMonitor();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "start floaw monitor failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::StopFlowMonitor()
{
    SLE_LOGD("StartFlowMonitor In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_NOT_READY, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed(%{public}d)!", ret);
    ret = pimpl_->StopFlowMonitor();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "stop floaw monitor failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleHostServer::GetHostDefaultConnectConfig(SleConnectConfig &hostConnParam)
{
    SLE_LOGD("GetHostDefaultConnectConfig In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_NOT_READY, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed(%{public}d)!", ret);
    ret = pimpl_->GetHostDefaultConnectConfig(hostConnParam);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "get host connect config failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

sptr<IRemoteObject> SleHostServer::GetSleServerRemote(const std::string &name)
{
    SLE_LOGD("GetSleServerRemote %{public}s ", name.c_str());
    if (!pimpl_) {
        SLE_LOGE("pimpl null error!");
        return nullptr;
    }
    return pimpl_->GetSleServerRemote(name);
}
} // SleStandard
} // NearLink
} // OHOS